<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 后台核心类
 *
 * @author ry
 *        
 */
class Admin {
	protected $CI;
	public $id;
	public function __construct() {
		$this->CI = & get_instance (); // 调用CI核心对象
		$this->CI->load->model ( 'admin_model' );
	}
	/**
	 * 登记管理员登录状态
	 *
	 * @param string $id        	
	 */
	public function login($id) {
		$this->CI->load->library ( 'session' );
		if (! empty ( $id )) {
			$this->CI->session->set_userdata ( 'admin_id', $id );
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 登录检测
	 *
	 * @param string $id        	
	 * @param string $url        	
	 * @return boolean
	 */
	public function isLogin($url = '') {
		$this->CI->load->library ( 'session' );
		$v = $this->CI->session->userdata ( 'admin_id' );
		if (empty ( $v ) && empty ( $url )) {
			return FALSE;
		} elseif (empty ( $v )) {
			redirect ( $url );
		} else {
			$this->id = $v;
			return TRUE;
		}
	}
	
	/**
	 * 设置错误码信息
	 *
	 * @param string $code        	
	 */
	public function setErr($code) {
		$this->CI->load->library ( 'session' );
		if (! empty ( $code )) {
			$this->CI->session->set_flashdata ( 'err', $code );
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 闪出错误信息
	 */
	public function flashErr() {
		$this->CI->load->library ( 'session' );
		$err = $this->CI->session->flashdata ( 'err' );
		echo $err;
	}
	/**
	 * 显示错误信息
	 */
	public function showErr() {
		$this->CI->load->library ( 'session' );
		$this->session->keep_flashdata ( 'err' );
		$err = $this->CI->session->flashdata ( 'err' );
		echo $err;
	}
	/**
	 * 验证是否存在该管理员
	 *
	 * @param string $id        	
	 */
	public function isExistAdmin($id) {
		$whereArr = array(
				'id' => $id 
		);
		$re = $this->CI->admin_model->count ( $whereArr );
		if ($re > 0) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 验证管理员密码
	 *
	 * @param array $whereArr        	
	 * @param string $password        	
	 */
	public function adminPwd($id, $password) {
		$whereArr = array(
				'id' => $id 
		);
		$re = $this->CI->admin_model->row ( $whereArr );
		if (is_array ( $re ) && $password === $this->_decrypt ( $re['password'] )) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 密码加密
	 */
	private function _encrypt($str) {
		$this->CI->load->library ( 'encrypt' );
		$re = $this->CI->encrypt->encode ( $str );
		return $re;
	}
	/**
	 * 密码解密
	 */
	private function _decrypt($str) {
		$this->CI->load->library ( 'encrypt' );
		$re = $this->CI->encrypt->decode ( $str );
		return $re;
	}
}